{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "\n",
    "\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "# Definition for singly-linked list.\n",
    "class ListNode:\n",
    "    def __init__(self, x):\n",
    "        self.val = x\n",
    "        self.next = None\n",
    "\n",
    "'''\n",
    "          p_1    curr       p_2  tail\n",
    "           |      |          |     |\n",
    "           V      V          V     V\n",
    "     ...->node  node->....->node->node->....\n",
    "           |                       ^\n",
    "           |                       |\n",
    "           +-----------------------+\n",
    "'''\n",
    "\n",
    "class Solution:\n",
    "    def reverseBetween(self, head: ListNode, m: int, n: int) -> ListNode:\n",
    "        H = ListNode(0)\n",
    "        H.next = head\n",
    "        p_1 = H\n",
    "        for i in range(m-1):\n",
    "            p_1 = p_1.next # p_1指向第m-1个节点\n",
    "        p_2 = p_1.next\n",
    "        for i in range(n-m):\n",
    "            p_2 = p_2.next #p_2指向第n个节点\n",
    "        tail = p_2.next\n",
    "        curr = p_1.next\n",
    "        p_1.next = tail\n",
    "        while(curr != tail): #将需要倒置的节点依次插入到p_1后面\n",
    "            temp = curr.next\n",
    "            curr.next = p_1.next\n",
    "            p_1.next = curr\n",
    "            curr = temp\n",
    "        return H.next"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.7.4"
  },
  "varInspector": {
   "cols": {
    "lenName": 16,
    "lenType": 16,
    "lenVar": 40
   },
   "kernels_config": {
    "python": {
     "delete_cmd_postfix": "",
     "delete_cmd_prefix": "del ",
     "library": "var_list.py",
     "varRefreshCmd": "print(var_dic_list())"
    },
    "r": {
     "delete_cmd_postfix": ") ",
     "delete_cmd_prefix": "rm(",
     "library": "var_list.r",
     "varRefreshCmd": "cat(var_dic_list()) "
    }
   },
   "types_to_exclude": [
    "module",
    "function",
    "builtin_function_or_method",
    "instance",
    "_Feature"
   ],
   "window_display": false
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
